﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Shweet.Repository;

namespace Shweet.Engine
{
    public class Reader
    {
        readonly IShweetMessages _shweetMessages;
        private readonly ITeams _shweetTeams;
        
        public Reader(IShweetMessages shweetMessages, ITeams shweetTeams)
        {
            Contract.Requires(shweetMessages != null);
            Contract.Requires(shweetTeams != null);

            _shweetMessages = shweetMessages;
            _shweetTeams = shweetTeams;
        }

        public Repository.Shweet[] Read(string[] tags)
        {
            Contract.Requires(tags != null);
            Contract.Requires(tags.All(tag => (tag != null)));
            Contract.Ensures(Contract.Result<Repository.Shweet[]>() != null);

            var shweets = new List<Repository.Shweet>();

            GetShweetsFromFollowedTeams(tags, shweets);
            GetShweetsFromCurrentTeam(tags, shweets);

            var sortedShweets = from s in shweets
                                orderby s.ShweetedOn descending 
                                select s;
            return sortedShweets.Take(30).ToArray();
        }

        private void GetShweetsFromCurrentTeam(string[] tags, List<Repository.Shweet> shweets)
        {
            shweets.InsertRange(0, _shweetMessages.Load(tags));
        }

        private void GetShweetsFromFollowedTeams(string[] tags, List<Repository.Shweet> shweets)
        {
            Repository.Shweet[] currentShweets;
            List<Team> teams = _shweetTeams.GetAll();
            foreach (var team in teams.Where(team => team.Following && team.Url != null))
            {
                currentShweets = _shweetMessages.Load(tags, team.Url);
                if (currentShweets != null)
                {
                    shweets.InsertRange(0, currentShweets);    
                }
            }
        }
    }
}
